﻿import * as fs from 'fs';
import Axios from 'axios';
import { Row, DataAction } from "./data";
import { Response, District } from './models';



const dataAction = new DataAction();

const keys = ['3387f2aae76ebd4f915de5ade19634dc', '806178332e93277d48d196c6981d3598', '35ea21e11d1a80d9ef41014a1b8513b4',
    '27b4b0aeb8dd4c32614f13d3e3fd866f', '09ee92217380c74c07119fbc31191078', '188237b34dde0db2acdb536db5763df9',
    '5f9f8a5b20757d48f26cce0125f3f24d', '93495dcc4cc8085550fff629c000616e', 'fb206e2bb6c03d6d021de271c64b3d3d'];

class GeoAction {

    private constructor() {

    }


    /**
     * 查询
     * @param adcode
     */
    private async serachFromAMap(adcode: number): Promise<District> {
        let key = keys[Math.floor(Math.random() * keys.length)];
        let url = `http://restapi.amap.com/v3/config/district?key=${key}&subdistrict=1&extensions=all&keywords=${adcode}`;
        let data = await Axios.get(url).then(response => response.data);
        while (true) {
            if (data.infocode !== '10000') {
                console.log(`KEY[${key}]失效`, data.infocode, data.info);
                keys.splice(keys.indexOf(key), 1);
                key = keys[Math.floor(Math.random() * keys.length)];
                url = `http://restapi.amap.com/v3/config/district?key=${key}&subdistrict=1&extensions=all&keywords=${adcode}`;
                data = await Axios.get(url).then(response => response.data);
            } else {
                break;
            }
        }
        return data.count === '1' ? data.districts[0] : null;
    }



    private async loopHandle(adcode: number, parentId: number): Promise<void> {

        const district = await this.serachFromAMap(adcode);
        for (var i = 0; i < district.districts.length; i++) {
            const item = district.districts[i];
            const row: Row = { ...item, parentId: parentId };
            delete row["districts"];
            row.polyline = "";
            if (row.citycode == null || (row.citycode as unknown as Array<any>).length < 1) row.citycode = 0;
            console.log(`开始写入数据:${JSON.stringify(row)}`);
            const insertedId = await dataAction.insert(row);  
            if (district.polyline && district.polyline != "") {

                if (parentId > 0) {
                    console.log(`开始更新polyline:${parentId}`);
                    const isHas = await dataAction.updatePolyline(parentId, district.polyline);
                }
                this.loopHandle(item.adcode, insertedId);
            }

        }
       
    }

    static async run() {
        await dataAction.init();
        const goeAction = new GeoAction();
        goeAction.loopHandle(100000, 0);

    }
}
export {

    GeoAction
};